from django_logs.models import AccessLog
from django_logs.models import Site
import logging
import re
import httpagentparser
import os
import os.path
import time

# Get an instance of a logger
logger = logging.getLogger(__name__)

def insert_access_log_entry(sitename, access_log_file, ip_address, date_time,request_method, resource, response_code, size, referer, operating_sys, dist, dist_version, browser, browser_version,user_agent):
	access_log = AccessLog()
	try:
           site = Site.objects.get(name=sitename)
	except(DoesNotExist):
	   logger.error('Error in retreiving site')
 	   site = Site(name=sitename,file_name=access_log_file)
	   site.save()
	   pass
	print site

  	#if(not site):
        #        logger.error('Error in retreiving site')
        #		site = Site(name=sitename,file_name=access_log_file)
	#	site.save()
        #       return

	access_log.site = site
	access_log.ip_address = ip_address
	access_log.date_time = date_time 
	access_log.request_method = request_method
	access_log.resource = resource
	access_log.response_code = response_code
	access_log.size = size
	access_log.referer = referer
	access_log.operating_sys = operating_sys
	access_log.dist = dist
	access_log.dist_version = dist_version
	access_log.browser = browser
	access_log.browser_version = browser_version
	access_log.user_agent = user_agent
	access_log.save()

def get_os(user_agent):
    user_agent = httpagentparser.detect(user_agent)
    operating_sys = ''
    if(user_agent['os']):
        if(user_agent['os']['name']):
                operating_sys = user_agent['os']['name']
    return operating_sys

def get_dist(user_agent):
    user_agent = httpagentparser.detect(user_agent)
    dist = ''
    if(user_agent['dist']):
        if(user_agent['dist']['name']):
                dist = user_agent['dist']['name']
    return dist

def get_dist_version(user_agent):
    user_agent = httpagentparser.detect(user_agent)
    dist_version = ''
    if(user_agent['dist']):
        if(user_agent['dist']['version']):
                dist_version = user_agent['dist']['version']
    return dist_version


def get_browser_name(user_agent):
    user_agent = httpagentparser.detect(user_agent)
#    print user_agent
    browser = ''
    if(user_agent['browser']):
        if(user_agent['browser']['name']):
           browser = user_agent['browser']['name']
    return browser

def get_browser_version(user_agent):
    user_agent = httpagentparser.detect(user_agent)
    version = ''
    if(user_agent['browser']):
        if(user_agent['browser']['version']):
           version = user_agent['browser']['version']
    return version
